from src.models.BaseModel import BaseModel
from peewee import *
from src.entry.Entrys import Page
from src.util.Model2Dict import m2d

""" 系统日志 """


class SysHandleLog(BaseModel):
    lId = BigIntegerField(db_column='l_id', primary_key=True)
    handleName = CharField(db_column='handle_name')
    time = DateTimeField()
    key = CharField()
    resp = TextField()
    req = TextField()
    username = CharField()
    status = IntegerField()
    ip = CharField()
    token = CharField()
    path = CharField()
    hid = BigIntegerField()

    class Meta:
        table_name = 'sys_handle_log'

    """ 获取所有的日志信息 """

    @staticmethod
    def getAllHandleLog(page: Page or None = None, cdn: dict = None, ids: list[int] = None):
        if cdn is None:
            cdn = dict()
        query = SysHandleLog.select()
        if cdn.get('username'):
            query = query.where(SysHandleLog.username.startswith(cdn.get('username')))
        if cdn.get('hid'):
            query = query.where(SysHandleLog.hid.in_(cdn.get('hid')))
        if ids is not None:
            query = query.where(SysHandleLog.hid.in_(ids))
        if cdn.get('time'):
            t: list[str] = cdn.get('time')
            if t[0]:
                query = query.where(SysHandleLog.time > t[0])
            if t[1]:
                query = query.where(SysHandleLog.time < t[1])
        if cdn.get('order'):
            order: dict = cdn.get('order')
            if order.get('time') and order.get('time') == 'asc':
                query = query.order_by(SysHandleLog.time.asc())
            if order.get('time') and order.get('time') == 'desc':
                query = query.order_by(SysHandleLog.time.desc())
        if page is None:
            r = query.dicts()
            return m2d(r)
        else:
            r = query.paginate(page.num, page.size).dicts()
            page.count = query.count()
            page.rows = m2d(r)
            return page.__dict__

    """ 更新某个日志的属性 """

    @staticmethod
    def updateHandleLog(id: int, k):
        return SysHandleLog.update(k).where(SysHandleLog.lId == id).execute() > 0

    """ 删除某日志 """

    # 按条件清除
    @staticmethod
    def clearLog(lids: list[int] = None, cdn: dict = None):
        if cdn is None:
            cdn = dict()
        q = SysHandleLog.delete()
        if lids is not None:
            q = q.where(SysHandleLog.lId.in_(lids))
        if cdn.get('username'):
            q = q.where(SysHandleLog.username == cdn.get('username'))
        if cdn.get('hids'):
            q = q.where(SysHandleLog.hid.in_(cdn.get('hids')))
        q.execute()
        return True

    """ 添加某日志 """

    @staticmethod
    def addHandleLog(d: dict):
        return SysHandleLog.insert(d).execute()
